package com.hoshiicloud.shxping.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.controller.BaseController;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.LBSUtil;
import com.hoshiicloud.goods.param.spu.ExtSpuQueryParam;
import com.hoshiicloud.shxping.dto.ConsumerDto;
import com.hoshiicloud.shxping.dto.MemberAddressDto;
import com.hoshiicloud.shxping.dto.PlatStoreDTO;
import com.hoshiicloud.shxping.feign.GoodsFeignService;
import com.hoshiicloud.shxping.feign.IUserFeignService;
import com.hoshiicloud.shxping.feign.OrderFeignService;
import com.hoshiicloud.shxping.param.PlatStoreQueryParam;
import com.hoshiicloud.shxping.param.StoreQueryParam;
import com.hoshiicloud.shxping.vo.CategoryGoodsVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yangcheng
 * @version 1.0
 * @title: StoreController
 * @description: 店铺Controller
 * @date 2019/6/10 0:55
 * @mail maiboyc@163.com
 */
@Slf4j
@RestController
@RequestMapping("/store")
@Api(value = "店铺管理", tags = {"店铺管理相关接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class StoreController extends BaseController {

    // 商品微服务Service
    @Resource
    private GoodsFeignService goodsFeignService;

    // 用户中心微服务Service
    @Resource
    private IUserFeignService userFeignService;

    // 订单微服务Service
    @Autowired
    private OrderFeignService orderFeignService;

    /**
     * 根据经纬度分页查询范围内的店铺列表同时包含商品信息
     * @param entity     经度
     * @return Response<Page<StoreRangeCalculationDTO>>
     */
    @PostMapping(value = "/storeRangeCalculation")
    @ApiOperation(value = "分页查询范围内店铺列表", notes = "分页查询范围店铺列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<Map<String,Object>>> StoreRangeCalculation(@RequestBody StoreQueryParam entity) {
        BigDecimal longitudeTemp = new BigDecimal(entity.getLongitude());
        BigDecimal latitudeTemp = new BigDecimal(entity.getLatitude());
        PlatStoreQueryParam platStoreQueryParam = new PlatStoreQueryParam();
        platStoreQueryParam.setPlatId(entity.getPlatId());
        platStoreQueryParam.setLongitude(longitudeTemp);
        platStoreQueryParam.setLatitude(latitudeTemp);
        platStoreQueryParam.setPageNumber(entity.getPageNumber());
        platStoreQueryParam.setPageSize(entity.getPageSize());
        Response<Page<Map<String,Object>>> rs = userFeignService.storeRange(platStoreQueryParam);
        return rs;
    }

    /**
     * 获取当前定位最近的一家店铺(带商品信息)
     * @param entity 查询参数
     * @return Response<Map<String,Object>>
     */
    @PostMapping(value = "/getNearestStore")
    @ApiOperation(value = "获取当前定位最近的一家店铺", notes = "获取当前定位最近的一家店铺", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Map<String,Object>> getNearestStore(@RequestBody StoreQueryParam entity) {
        Response<Map<String,Object>> result = new Response<>();
        BigDecimal longitudeTemp = new BigDecimal(entity.getLongitude());
        BigDecimal latitudeTemp = new BigDecimal(entity.getLatitude());
        PlatStoreQueryParam platStoreQueryParam = new PlatStoreQueryParam();
        platStoreQueryParam.setPlatId(entity.getPlatId());
        platStoreQueryParam.setLongitude(longitudeTemp);
        platStoreQueryParam.setLatitude(latitudeTemp);
        platStoreQueryParam.setPageNumber(entity.getPageNumber());
        platStoreQueryParam.setPageSize(entity.getPageSize());
        Response<Page<Map<String,Object>>> rs = userFeignService.storeRange(platStoreQueryParam);
        if (null != rs && rs.getCode() == 200 && null != rs.getData().getRecords()){
            if (null != entity.getUserId()){
                Response<ConsumerDto> consumerDtoResponse = userFeignService.getConsumerById(entity.getUserId());
                if (null != consumerDtoResponse && consumerDtoResponse.getCode() ==200 && null != consumerDtoResponse.getData()) {
                    if (null != consumerDtoResponse.getData().getStoreId()) {
                        for (Map<String,Object> item: rs.getData().getRecords()) {
                            Long id = Long.valueOf((String)item.get("id"));
                            if(id == consumerDtoResponse.getData().getStoreId()){
                                result = Response.data(item);
                            }
                        }
                    } else {
                        result = Response.data(rs.getData().getRecords().get(0));
                    }
                }
            } else{
                result = Response.data(rs.getData().getRecords().get(0));
            }
        } else {
            log.error("范围查询分页查询失败，没有数据！");
            result = Response.failed("范围查询分页查询失败，没有数据");
        }
        return result;
    }

    @GetMapping(value = "query/{id}")
    @ApiOperation(value = "根据id查询店铺详情", notes = "根据id查询店铺详情", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<PlatStoreDTO> storeDetail(@PathVariable("id") Long id) {
        Response<PlatStoreDTO> response = userFeignService.queryById(id);
        // List<Long> funs = new ArrayList<>();
        // List<Long> buy_exponent = new ArrayList<>();
        if (null != response && response.getCode() == 200 && null != response.getData()) {
            // // 店铺粉丝数
            // OrderInfoQueryParam param1 = new OrderInfoQueryParam();
            // param1.setStoreId(id);
            // Response<List<OrderInfo>> orderInfoResponse = orderFeignService.listOrderInfos(param1);
            // for (OrderInfo orderInfo: orderInfoResponse.getData()) {
            //     if (!funs.contains(orderInfo.getMemberId())) {
            //         funs.add(orderInfo.getMemberId());
            //     }
            // }
            //
            // // 购买指数
            // OrderInfoQueryParam param2 = new OrderInfoQueryParam();
            // param2.setStoreId(id);
            // param2.setOrderStatus(2);
            // Response<List<OrderInfo>> orderInfoResponse2 = orderFeignService.listOrderInfos(param2);
            // for (OrderInfo orderInfo: orderInfoResponse2.getData()) {
            //         buy_exponent.add(orderInfo.getMemberId());
            // }
            Response<List<Map<String,Object>>> rs = orderFeignService.getStoreFansAndBuyExponentGroupById(2);
            if (null != rs && rs.getCode() == 200 && null != rs.getData() && rs.getData().size() > 0) {
                rs.getData().forEach(item -> {
                    if (response.getData().getId().equals(Long.parseLong(item.get("store_id").toString()))) {
                        response.getData().setFans(Integer.parseInt(item.get("fans").toString()));
                        response.getData().setBuyExponent(Integer.parseInt(item.get("sales_order").toString())*100);
                    }
                });
            }
            if (null == response.getData().getFans()) {
                response.getData().setFans(0);
            }
            if (null == response.getData().getBuyExponent()) {
                response.getData().setBuyExponent(0);
            }
        } else {
            log.error("根据id查询店铺详情失败，没有数据！");
            return Response.failed("根据id查询店铺详情失败，没有数据！");
        }
        return response;
    }

    /**
     * 根据店铺ID获取店铺经营类目
     * @param storeId 店铺Id
     * @return Response<List<Map<String,Object>>>
     */
    @GetMapping(value = "getCategoriesByStoreId/{storeId}")
    @ApiOperation(value = "根据店铺ID获取店铺经营类目", notes = "根据店铺ID获取店铺经营类目", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<Map<String,Object>>> getCategoriesByStoreId(@PathVariable("storeId") Long storeId) {
        Response<List<Map<String,Object>>> rs;
        try {
            rs = userFeignService.getCategoriesByStoreId(storeId);
        } catch (Exception e) {
            log.error("根据店铺ID获取店铺经营类目异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据店铺ID获取店铺经营类目异常"+"["+e.getMessage()+"]");
        }
        return rs;
    }

    /**
     * 返回类目加上商品列表（不分页）
     * @param param
     * {
     * 	"pageNumber": "1",
     * 	"pageSize": "5",
     * 	"platformid": 9609977215975480,
     * 	"storeId": 2
     * }
     * @return Response<List<CategoryGoodsVo>>
     */
    @PostMapping(value = "getCategoryAndGoods")
    @ApiOperation(value = "返回类目加上商品列表", notes = "返回类目加上商品列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<CategoryGoodsVo>> getCategoryAndGoods(@RequestBody ExtSpuQueryParam param) {
        Response<List<CategoryGoodsVo>> rs = new Response<>();
        try {
            Response<List<Map<String,Object>>> categories = userFeignService.getCategoriesByStoreId(param.getStoreId());
            if (null != categories && categories.getCode() == 200 && categories.getData().size() > 0) {
                List<CategoryGoodsVo> data = new ArrayList<>();
                categories.getData().forEach(item ->{
                    CategoryGoodsVo vo = new CategoryGoodsVo();
                    vo.setCategoryId(Long.parseLong((String) item.get("categoryId")));
                    vo.setCategoryName((String)item.get("name"));
                    param.setCategoryId(Long.parseLong((String) item.get("categoryId")));
                    Response<Page<Map<String,Object>>> goods = goodsFeignService.getSpusWithMiniPrice(param);
                    vo.setGoods(goods.getData().getRecords());
                    data.add(vo);
                });
                rs.setCode(categories.getCode());
                rs.setMsg(categories.getMsg());
                rs.setData(data);
            }
        } catch (Exception e) {
            log.error("根据店铺ID获取店铺经营类目异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据店铺ID获取店铺经营类目异常"+"["+e.getMessage()+"]");
        }
        return rs;
    }

    /**
     * 计算收货地址是否在店铺配送范围内
     * @param params 参数店铺ID和地址ID
     * @return Response<Boolean>
     */
    @ApiOperation(value = "计算收货地址是否在店铺配送范围内", notes = "计算收货地址是否在店铺配送范围内", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "params" , paramType = "body",examples = @Example({
            @ExampleProperty(value = "{'storeId': 123213, 'addressId': 456789}", mediaType = "application/json")
    }))
    @PostMapping("/addressWithinRange")
    public Response<Boolean> addressWithinRange(@RequestBody Map<String,Object> params) {
        Response<Boolean> rs;
        try {
            // 店铺ID
            Long storeId = (Long)params.get("storeId");
            // 收货地址ID
            Long addressId = (Long)params.get("addressId");
            Response<PlatStoreDTO> storeRs = userFeignService.queryById(storeId);
            Response<MemberAddressDto> addressRs = userFeignService.getAddressById(addressId);
            if (null != storeRs && storeRs.getCode() == 200 && null != storeRs.getData()) {
                if (null != addressRs && addressRs.getCode() == 200 && null != addressRs.getData()) {
                    BigDecimal storeLongitude = storeRs.getData().getLongitude();
                    BigDecimal storeLatitude = storeRs.getData().getLatitude();
                    BigDecimal addressLongitude = addressRs.getData().getLongitude();
                    BigDecimal addressLatitude = addressRs.getData().getLatitude();
                    Double distance = LBSUtil.getDistanceByLongitudeAndLatitude(storeLongitude.doubleValue(),storeLatitude.doubleValue(),addressLongitude.doubleValue(),addressLatitude.doubleValue());
                    if (distance > 2000) {
                        rs = Response.data(false);
                    } else {
                        rs = Response.data(true);
                    }
                } else {
                    rs = Response.failed("查询收货地址信息失败");
                }
            } else {
                rs = Response.failed("查询店铺信息失败");
            }

        } catch (Exception e) {
            rs = Response.failed("根据店铺ID获取店铺经营类目异常"+"["+e.getMessage()+"]");
        }
        return rs;
    }

    //根据用户ID返回店铺列表
    @PostMapping(value = "/getStoresByUserId")
    @ApiOperation(value = "根据用户ID返回店铺列表", notes = "根据用户ID返回店铺列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<PlatStoreDTO>> getStoresByUserId(@RequestBody PlatStoreQueryParam param) {
        Response<Page<PlatStoreDTO>> rs;
        try {
            rs = userFeignService.page(param);
        } catch (Exception e) {
            rs = Response.failed("根据店铺ID获取店铺经营类目异常"+"["+e.getMessage()+"]");
        }
        return rs;
    }

    /**
     * 根据平台ID获取所有店铺列表
     * @param platId 平台ID
     * @return Response<List<PlatStoreDTO>>
     */
    @GetMapping(value = "/getStoresByPlatId/{platId}")
    @ApiOperation(value = "根据平台ID获取所有店铺列表", notes = "根据平台ID获取所有店铺列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<PlatStoreDTO>> getStoresByPlatId(@PathVariable("platId") Long platId) {
        Response<List<PlatStoreDTO>> rs;
        try {
            rs = userFeignService.getStoresByPlatId(platId);
        } catch (Exception e) {
            rs = Response.failed("根据平台ID获取所有店铺列表异常"+"["+e.getMessage()+"]");
        }
        return rs;
    }

    /**
     * 批量更新店铺信息
     * @param storeDTOS 店铺列表
     * @return Response<List<Long>>
     */
    @PostMapping(value = "/batchUpdateStores")
    @ApiOperation(value = "批量更新店铺信息", notes = "批量更新店铺信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<Long>> batchUpdateStores(@RequestBody List<PlatStoreDTO> storeDTOS) {
        Response<List<Long>> rs;
        try {
            rs = userFeignService.batchUpdateStores(storeDTOS);
        } catch (Exception e) {
            rs = Response.failed("批量更新店铺信息异常" + "[" + e.getMessage() + "]");
        }
        return rs;
    }


}
